<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="120px">
      <el-form-item label="采购订单编号" prop="orderNo">
        <el-input
          v-model="queryParams.orderNo"
          placeholder="请输入采购订单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供货商编码" prop="supplierCode">
        <el-input
          v-model="queryParams.supplierCode"
          placeholder="请输入供货商编码"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:purchase_order:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:purchase_order:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:purchase_order:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:purchase_order:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="purchase_orderList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" fixed="left" />
      <el-table-column type="index" label="序号" width="60" align="center" :index="computeIndex" fixed="left" />
      <el-table-column label="明细状态" align="center" prop="itemStatus" min-width="140" fixed="left">
        <template slot-scope="scope">
          <el-tag :color="statusColor(scope.row.itemStatus)" effect="dark" size="small" class="status-tag">
            <i class="status-dot" :style="{ backgroundColor: statusColor(scope.row.itemStatus) }"></i>
            {{ itemStatusMap[scope.row.itemStatus] || scope.row.itemStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="采购订单编号" align="center" prop="orderNo" min-width="160" />
      <el-table-column label="供货商编码" align="center" prop="supplierCode" min-width="140" />
      <el-table-column label="供货商名称" align="center" prop="supplierName" min-width="160" />
      <el-table-column label="存货编码" align="center" prop="inventoryCode" min-width="140" />
      <el-table-column label="存货名称" align="center" prop="inventoryName" min-width="180" />
      <el-table-column label="订单数量" align="center" prop="orderQuantity" min-width="120" />
      <el-table-column label="计量单位名称" align="center" prop="unitName" min-width="120" />
      <el-table-column label="已打码数量" align="center" prop="barcodedQuantity" min-width="140" />
      <el-table-column label="未打码数量" align="center" prop="unbarcodedQuantity" min-width="140" />
      <el-table-column label="已入库数量" align="center" prop="putawayQuantity" min-width="140" />
      <el-table-column label="采购时间" align="center" prop="purchaseDate" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchaseDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购人" align="center" prop="purchaser" min-width="120" />
      <el-table-column label="交货时间" align="center" prop="deliveryDate" width="200">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="240">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="info"
            icon="el-icon-search"
            style="border-radius: 18px; padding: 6px 12px; margin-right: 8px;"
            @click="viewBarcodes(scope.row)"
            v-if="Number(scope.row.barcodedQuantity) > 0"
          >查看箱码</el-button>
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-circle-check"
            style="border-radius: 18px; padding: 6px 12px;"
            @click="openGenerateBarcodeDialog(scope.row)"
            v-if="Number(scope.row.unbarcodedQuantity) > 0"
          >生成箱码</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:purchase_order:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:purchase_order:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改采购订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <!-- 移除：采购订单编号（改为后端自动生成） -->
        
        <!-- 主表信息：两列布局，每行两个 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="供货商编码" prop="supplierCode">
              <el-select v-model="form.supplierCode" filterable remote reserve-keyword placeholder="请选择供货商"
                :remote-method="remoteSearchSupplier" :loading="supplierLoading" style="width:100%"
                @change="handleSupplierChange" @visible-change="onSupplierDropdownVisible">
                <el-option v-for="opt in supplierOptions" :key="opt.supplierCode"
                  :label="`${opt.supplierName}（${opt.supplierCode}）`" :value="opt.supplierCode" />
              </el-select>
            </el-form-item>
            
          </el-col>
          <el-col :span="12">
            <el-form-item label="采购时间" prop="purchaseDate">
              <el-date-picker clearable
                v-model="form.purchaseDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择采购时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购人" prop="purchaser">
              <el-input v-model="form.purchaser" placeholder="请输入采购人" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="交货时间" prop="deliveryDate">
              <el-date-picker clearable
                v-model="form.deliveryDate"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择交货时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-divider content-position="center">采购订单明细信息</el-divider>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAddBizPurchaseOrderItem">添加</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="handleDeleteBizPurchaseOrderItem">删除</el-button>
          </el-col>
        </el-row>
        <el-table :data="bizPurchaseOrderItemList" :row-class-name="rowBizPurchaseOrderItemIndex" @selection-change="handleBizPurchaseOrderItemSelectionChange" ref="bizPurchaseOrderItem">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <!-- 存货编码改为可搜索下拉 -->
          <el-table-column label="存货编码" prop="inventoryCode" width="220">
            <template slot-scope="scope">
              <el-select v-model="scope.row.inventoryCode" filterable remote reserve-keyword placeholder="请选择存货"
                :remote-method="remoteSearchInventory" :loading="inventoryLoading" style="width:200px"
                @change="handleInventoryChange(scope.row)" @visible-change="onInventoryDropdownVisible">
                <el-option v-for="opt in inventoryOptions" :key="opt.inventoryCode"
                  :label="`${opt.inventoryName || opt.supplierInventoryName || opt.inventoryCode}（${opt.inventoryCode}）`" :value="opt.inventoryCode" />
              </el-select>
            </template>
          </el-table-column>

          <el-table-column label="订单数量" prop="orderQuantity" width="150">
            <template slot-scope="scope">
              <el-input v-model="scope.row.orderQuantity" placeholder="请输入订单数量" />
            </template>
          </el-table-column>
          <!-- 计量单位编码改为可搜索下拉 -->
          <el-table-column label="计量单位编码" prop="unitCode" width="220">
            <template slot-scope="scope">
              <el-select v-model="scope.row.unitCode" filterable remote reserve-keyword placeholder="请选择计量单位"
                :remote-method="remoteSearchUnit" :loading="unitLoading" style="width:200px"
                @change="handleUnitChange(scope.row)" @visible-change="onUnitDropdownVisible">
                <el-option v-for="opt in unitOptions" :key="opt.unitCode"
                  :label="`${opt.unitName}（${opt.unitCode}）`" :value="opt.unitCode" />
              </el-select>
            </template>
          </el-table-column>

        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 生成箱码弹窗 -->
    <el-dialog title="生成箱码" :visible.sync="openGenerateDialog" width="900px" append-to-body>
      <el-form ref="generateFormRef" :model="generateForm" :rules="generateRules" label-width="160px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="采购订单编号" prop="orderNo">
              <el-input v-model="generateForm.orderNo" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="未打码个数">
              <el-input v-model="generateForm.unbarcodedQuantity" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <!-- 新增：批次号展示（今日日期+序号） -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="批次号">
              <el-input v-model="generateForm.batchNo" disabled />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="标箱数量" prop="stdPerBox">
              <el-input-number v-model="generateForm.stdPerBox" :min="1" controls-position="right" @change="onStdChange" style="width:100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="本次打码数量" prop="encodeQuantity">
              <el-input-number v-model="generateForm.encodeQuantity" :min="1" controls-position="right" @change="onEncodeChange" style="width:100%" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="箱数">
              <el-input :value="generateForm.boxes" disabled />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="发货日期" prop="deliveryDate">
              <el-date-picker clearable v-model="generateForm.deliveryDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择发货日期" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitGenerate">确 定</el-button>
        <el-button @click="cancelGenerate">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listPurchase_order, listPurchaseOrderItems, getPurchase_order, delPurchase_order, addPurchase_order, updatePurchase_order } from "@/api/system/purchase_order"
// 新增：获取下拉数据的接口
import { listSupplier } from "@/api/system/supplier"
import { listInventory } from "@/api/system/inventory"
import { listUnit } from "@/api/system/unit"
import { listInventory_supplier } from "@/api/system/inventory_supplier"
import { generateBarcode, getNextBatchNo } from "@/api/system/barcode"

export default {
  name: "Purchase_order",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 子表选中数据
      checkedBizPurchaseOrderItem: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采购订单表格数据
      purchase_orderList: [],
      // 采购订单明细表格数据
      bizPurchaseOrderItemList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderNo: null,
        supplierCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // 移除订单编号必填校验，保留供货商编码与采购时间
        supplierCode: [
          { required: true, message: "供货商编码不能为空", trigger: "blur" }
        ],
        purchaseDate: [
          { required: true, message: "采购时间不能为空", trigger: "blur" }
        ],
      },
      // 下拉选项与加载状态
      supplierOptions: [],
      supplierLoading: false,
      inventoryOptions: [],
      inventoryLoading: false,
      unitOptions: [],
      unitLoading: false,
      
      // 明细状态枚举显示映射
      itemStatusMap: {
        '0': '待处理',
        '1': '部分收货',
        '2': '全部收货',
        '3': '质检中',
        '4': '质检合格',
        '5': '质检不合格',
        '6': '部分入库',
        '7': '全部入库',
        '8': '已完成',
        PENDING: '待处理',
        PART_RECEIVED: '部分收货',
        FULL_RECEIVED: '全部收货',
        QUALITY_CHECK: '质检中',
        QUALITY_PASSED: '质检合格',
        QUALITY_FAILED: '质检不合格',
        PART_PUTAWAY: '部分入库',
        FULL_PUTAWAY: '全部入库',
        COMPLETED: '已完成'
      },
      
      // 生成箱码弹窗
      openGenerateDialog: false,
      generateForm: {
        orderNo: '',
        itemId: null,
        stdPerBox: null,
        encodeQuantity: null,
        boxes: 0,
        deliveryDate: null,
        unbarcodedQuantity: 0,
        batchNo: ''
      },
      generateRules: {
        stdPerBox: [
          { required: true, message: '标箱数量不能为空', trigger: 'blur' }
        ],
        encodeQuantity: [
          { required: true, message: '本次打码数量不能为空', trigger: 'blur' }
        ],
        deliveryDate: [
          { required: true, message: '发货日期不能为空', trigger: 'change' }
        ]
      },
    }
  },
  created() {
    this.getList()
  },
  methods: {
    // 主表列表序号计算（跨页连续序号）
    computeIndex(index) {
      return (this.queryParams.pageSize * (this.queryParams.pageNum - 1)) + index + 1
    },
    // 新增：根据状态返回徽章类型
    statusType(code) {
      const c = String(code || '').toUpperCase()
      const map = {
        '0': 'info',
        '1': 'warning',
        '2': 'success',
        '3': 'warning',
        '4': 'success',
        '5': 'danger',
        '6': 'warning',
        '7': 'success',
        '8': 'success',
        'PENDING': 'info',
        'PART_RECEIVED': 'warning',
        'FULL_RECEIVED': 'success',
        'QUALITY_CHECK': 'warning',
        'QUALITY_PASSED': 'success',
        'QUALITY_FAILED': 'danger',
        'PART_PUTAWAY': 'warning',
        'FULL_PUTAWAY': 'success',
        'COMPLETED': 'success'
      }
      return map[c] || 'info'
    },
    // 新增：根据状态返回自定义颜色（每个枚举唯一）
    statusColor(code) {
      const c = String(code || '').toUpperCase()
      const normalized = {
        '0': 'PENDING',
        '1': 'PART_RECEIVED',
        '2': 'FULL_RECEIVED',
        '3': 'QUALITY_CHECK',
        '4': 'QUALITY_PASSED',
        '5': 'QUALITY_FAILED',
        '6': 'PART_PUTAWAY',
        '7': 'FULL_PUTAWAY',
        '8': 'COMPLETED'
      }[c] || c
      const colorMap = {
        PENDING: '#95A5A6',        // 待处理：中性灰
        PART_RECEIVED: '#F39C12',  // 部分收货：琥珀橙
        FULL_RECEIVED: '#27AE60',  // 全部收货：翠绿
        QUALITY_CHECK: '#3498DB',  // 质检中：清澈蓝
        QUALITY_PASSED: '#3B82F6', // 质检合格：亮蓝
        QUALITY_FAILED: '#E74C3C', // 质检不合格：警示红
        PART_PUTAWAY: '#9B59B6',  // 部分入库：紫色
        FULL_PUTAWAY: '#16A085',  // 全部入库：深青
        COMPLETED: '#2ECC71'      // 已完成：翡翠绿
      }
      return colorMap[normalized] || '#909399'
    },
    /** 查询采购订单列表 */
    getList() {
      this.loading = true
      listPurchaseOrderItems(this.queryParams).then(response => {
        this.purchase_orderList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        orderId: null,
        orderNo: null,
        supplierCode: null,
        purchaseDate: null,
        purchaser: null,
        deliveryDate: null,
        totalQuantity: null,
        totalBarcoded: null,
        totalUnbarcoded: null,
        totalPutaway: null,
        orderStatus: null,
        createdBy: null,
        createdTime: null,
        updatedBy: null,
        updatedTime: null,
        remark: null,
        delFlag: null,
        // 展示用的名称
        _supplierName: null,
      }
      this.bizPurchaseOrderItemList = []
      this.resetForm("form")
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.orderId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = "添加采购订单"
      // 初次弹出时加载初始下拉项
      this.remoteSearchSupplier("")
      this.remoteSearchInventory("")
      this.remoteSearchUnit("")
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      const orderId = row.orderId || this.ids
      getPurchase_order(orderId).then(response => {
        this.form = response.data
        // 展示选中的供货商名称
        this.fetchSupplierNameByCode(this.form.supplierCode)
        this.bizPurchaseOrderItemList = response.data.bizPurchaseOrderItemList
        // 为每行补充显示名称
        if (Array.isArray(this.bizPurchaseOrderItemList)) {
          this.bizPurchaseOrderItemList.forEach(r => {
            this.fetchInventoryNameByCode(r)
            this.fetchUnitNameByCode(r)
          })
        }
        this.open = true
        this.title = "修改采购订单"
        // 弹窗打开时，准备下拉选项
        this.remoteSearchSupplier("")
        this.remoteSearchInventory("")
        this.remoteSearchUnit("")
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 明细赋值
          this.form.bizPurchaseOrderItemList = this.bizPurchaseOrderItemList
          // 计算：订单总数量 = 明细采购数量总和
          const totalQty = Array.isArray(this.bizPurchaseOrderItemList)
            ? this.bizPurchaseOrderItemList.reduce((sum, r) => sum + Number(r.orderQuantity || 0), 0)
            : 0
          this.form.totalQuantity = totalQty
          // 计算：总已打码数量 = 0；总未打码数量 = 总数量 - 总已打码数量
          this.form.totalBarcoded = 0
          this.form.totalUnbarcoded = Number(totalQty) - Number(this.form.totalBarcoded || 0)
          // 计算：总已入库数量 = 0
          this.form.totalPutaway = 0

          if (this.form.orderId != null) {
            updatePurchase_order(this.form).then(response => {
              this.$modal.msgSuccess("修改成功")
              this.open = false
              this.getList()
            })
          } else {
            addPurchase_order(this.form).then(response => {
              this.$modal.msgSuccess("新增成功")
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const orderIds = row.orderId || this.ids
      this.$modal.confirm('是否确认删除采购订单编号为"' + orderIds + '"的数据项？').then(function() {
        return delPurchase_order(orderIds)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess("删除成功")
      }).catch(() => {})
    },
	/** 采购订单明细序号 */
    rowBizPurchaseOrderItemIndex({ row, rowIndex }) {
      row.index = rowIndex + 1
    },
    /** 采购订单明细添加按钮操作 */
    handleAddBizPurchaseOrderItem() {
      let obj = {}
      // 仅保留业务需要的三个输入字段
      obj.inventoryCode = ""
      obj.orderQuantity = ""
      obj.unitCode = ""
      // 展示用名称
      obj._inventoryName = ""
      obj._unitName = ""
      this.bizPurchaseOrderItemList.push(obj)
    },
    /** 采购订单明细删除按钮操作 */
    handleDeleteBizPurchaseOrderItem() {
      if (this.checkedBizPurchaseOrderItem.length == 0) {
        this.$modal.msgError("请先选择要删除的采购订单明细数据")
      } else {
        const bizPurchaseOrderItemList = this.bizPurchaseOrderItemList
        const checkedBizPurchaseOrderItem = this.checkedBizPurchaseOrderItem
        this.bizPurchaseOrderItemList = bizPurchaseOrderItemList.filter(function(item) {
          return checkedBizPurchaseOrderItem.indexOf(item.index) == -1
        })
      }
    },
    /** 复选框选中数据 */
    handleBizPurchaseOrderItemSelectionChange(selection) {
      this.checkedBizPurchaseOrderItem = selection.map(item => item.index)
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/purchase_order/export', {
        ...this.queryParams
      }, `purchase_order_${new Date().getTime()}.xlsx`)
    },
    // 远程搜索：供货商
    remoteSearchSupplier(query) {
      this.supplierLoading = true
      const params = { pageNum: 1, pageSize: 10 }
      if (query) params.supplierName = query
      listSupplier(params).then(resp => {
        this.supplierOptions = resp.rows || []
      }).finally(() => { this.supplierLoading = false })
    },
    onSupplierDropdownVisible(visible) {
      if (visible) this.remoteSearchSupplier("")
    },
    handleSupplierChange(val) {
      const hit = this.supplierOptions.find(s => s.supplierCode === val)
      this.form._supplierName = hit ? hit.supplierName : ''
      // 供货商变化时，清空明细中的存货选择，避免跨供应商混选
      this.bizPurchaseOrderItemList.forEach(r => {
        r.inventoryCode = ''
        r._inventoryName = ''
      })
      // 重新按供货商过滤加载存货下拉
      this.remoteSearchInventory("")
    },
    fetchSupplierNameByCode(code) {
      if (!code) { this.form._supplierName = '' ; return }
      listSupplier({ pageNum: 1, pageSize: 1, supplierCode: code }).then(resp => {
        const r = (resp.rows || [])[0]
        this.form._supplierName = r ? r.supplierName : ''
      })
    },
    // 远程搜索：存货（按供货商过滤）
    remoteSearchInventory(query) {
      this.inventoryLoading = true
      const supplierCode = this.form.supplierCode
      if (supplierCode) {
        const params = { pageNum: 1, pageSize: 10, supplierCode }
        listInventory_supplier(params).then(resp => {
          let rows = resp.rows || []
          if (query) {
            const q = String(query).trim().toLowerCase()
            rows = rows.filter(r =>
              (r.inventoryCode || '').toLowerCase().includes(q) ||
              (r.supplierInventoryName || '').toLowerCase().includes(q)
            )
          }
          this.inventoryOptions = rows
        }).finally(() => { this.inventoryLoading = false })
      } else {
        const params = { pageNum: 1, pageSize: 10 }
        if (query) params.inventoryName = query
        listInventory(params).then(resp => {
          this.inventoryOptions = resp.rows || []
        }).finally(() => { this.inventoryLoading = false })
      }
    },
    onInventoryDropdownVisible(visible) {
      if (visible) this.remoteSearchInventory("")
    },
    handleInventoryChange(row) {
      const hit = this.inventoryOptions.find(i => i.inventoryCode === row.inventoryCode)
      row._inventoryName = hit ? (hit.inventoryName || hit.supplierInventoryName || '') : ''
      // 若本次下拉来源于供货商对照，仍用主存货表补充名称，保持显示一致
      this.fetchInventoryNameByCode(row)
    },
    fetchInventoryNameByCode(row) {
      if (!row || !row.inventoryCode) { row._inventoryName = '' ; return }
      listInventory({ pageNum: 1, pageSize: 1, inventoryCode: row.inventoryCode }).then(resp => {
        const r = (resp.rows || [])[0]
        row._inventoryName = r ? r.inventoryName : row._inventoryName
      })
    },
    // 远程搜索：计量单位
    remoteSearchUnit(query) {
      this.unitLoading = true
      const params = { pageNum: 1, pageSize: 10 }
      if (query) params.unitName = query
      listUnit(params).then(resp => {
        this.unitOptions = resp.rows || []
      }).finally(() => { this.unitLoading = false })
    },
    onUnitDropdownVisible(visible) {
      if (visible) this.remoteSearchUnit("")
    },
    handleUnitChange(row) {
      const hit = this.unitOptions.find(u => u.unitCode === row.unitCode)
      row._unitName = hit ? hit.unitName : ''
    },
    fetchUnitNameByCode(row) {
      if (!row || !row.unitCode) { row._unitName = '' ; return }
      listUnit({ pageNum: 1, pageSize: 1, unitCode: row.unitCode }).then(resp => {
        const r = (resp.rows || [])[0]
        row._unitName = r ? r.unitName : ''
      })
    },


    // 生成箱码：打开弹窗并初始化表单
    openGenerateBarcodeDialog(row) {
      this.openGenerateDialog = true
      this.generateForm.orderNo = row.orderNo || ''
      this.generateForm.itemId = row.itemId || null
      this.generateForm.unbarcodedQuantity = Number(row.unbarcodedQuantity || 0)
      this.generateForm.stdPerBox = null
      this.generateForm.encodeQuantity = null
      this.generateForm.boxes = 0
      this.generateForm.deliveryDate = null
      // 打开弹窗时从后端获取当日下个批次号
      this.generateForm.batchNo = '加载中...'
      getNextBatchNo().then(resp => {
        const data = resp && resp.data ? resp.data : {}
        const bn = data.batchNo || ''
        this.generateForm.batchNo = bn || '获取失败'
      }).catch(() => {
        this.generateForm.batchNo = '获取失败'
      })
    },
    onStdChange() {
      this.updateGenerateBoxes()
    },
    onEncodeChange() {
      this.updateGenerateBoxes()
    },
    updateGenerateBoxes() {
      const a = Number(this.generateForm.encodeQuantity || 0)
      const b = Number(this.generateForm.stdPerBox || 0)
      // 不整除则加 1，即向上取整
      this.generateForm.boxes = a > 0 && b > 0 ? Math.ceil(a / b) : 0
    },
    submitGenerate() {
      this.$refs['generateFormRef'].validate(async valid => {
        if (!valid) return
        const a = Number(this.generateForm.encodeQuantity || 0)
        const b = Number(this.generateForm.stdPerBox || 0)
        const unbarcoded = Number(this.generateForm.unbarcodedQuantity || 0)
        if (b <= 0) {
          this.$modal.msgError('标箱数量必须为正数')
          return
        }
        if (a <= 0) {
          this.$modal.msgError('本次打码数量必须为正数')
          return
        }
        if (a > unbarcoded) {
          this.$modal.msgError('本次打码数量不能超过未打码个数')
          return
        }
        this.updateGenerateBoxes()
        // 调用后端生成箱码接口
        const payload = {
          itemId: this.generateForm.itemId,
          encodeQuantity: this.generateForm.encodeQuantity,
          stdPerBox: this.generateForm.stdPerBox,
          deliveryDate: this.generateForm.deliveryDate,
        }
        try {
          const resp = await generateBarcode(payload)
          const data = resp && resp.data ? resp.data : {}
          const rows = Number(data.rows || 0)
          const batchNo = data.batchNo || ''
          this.$modal.msgSuccess(`生成成功，批次号：${batchNo}，共 ${rows} 条箱码`)

          // 新增：根据订单编号更新主表汇总（总已打码/总未打码）
          try {
            const orderNo = this.generateForm.orderNo || ''
            const listResp = await listPurchase_order({ pageNum: 1, pageSize: 1, orderNo })
            const header = (listResp && listResp.rows ? listResp.rows[0] : null)
            if (header && header.orderId != null) {
              const prevBarcoded = Number(header.totalBarcoded || 0)
              const totalQty = Number(header.totalQuantity || 0)
              const add = Number(this.generateForm.encodeQuantity || 0)
              const newTotalBarcoded = prevBarcoded + add
              const newTotalUnbarcoded = totalQty - newTotalBarcoded
              await updatePurchase_order({
                orderId: header.orderId,
                totalBarcoded: newTotalBarcoded,
                totalUnbarcoded: newTotalUnbarcoded
              })
              this.$modal.msgSuccess('主表汇总已更新')
            } else {
              this.$modal.msgWarning('未找到采购订单主表，汇总未更新')
            }
          } catch (err) {
            const m = (err && err.msg) || (err && err.message) || '更新主表汇总失败'
            this.$modal.msgError(m)
          }

          this.generateForm.batchNo = batchNo
          this.openGenerateDialog = false
          this.getList()
        } catch (e) {
          // 后端会抛 ServiceException，由全局拦截器包装为标准响应
          // 这里简单提示错误消息
          const msg = (e && e.msg) || (e && e.message) || '生成失败'
          this.$modal.msgError(msg)
        }
      })
    },
    cancelGenerate() {
      this.openGenerateDialog = false
    },
    // 查看箱码：跳转到箱码列表并按当前行明细ID过滤
    viewBarcodes(row) {
      const itemId = row && row.itemId
      if (!itemId) {
        this.$modal && this.$modal.msgError ? this.$modal.msgError('当前行缺少订单明细ID，无法查看箱码') : alert('当前行缺少订单明细ID，无法查看箱码')
        return
      }
      this.$router.push({ path: '/system/barcode', query: { itemId } })
    },
  }
}
</script>

<style scoped>
.status-tag {
  border-radius: 16px;
  padding: 0 10px;
  line-height: 22px;
  display: inline-flex;
  align-items: center;
}
.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}
/* 移除基于type的固定颜色，改为按状态动态渲染 */
</style>
